package com.ytjj.qmyx.supplychain.api.controller;

import com.alibaba.excel.metadata.Sheet;
import com.alibaba.excel.util.CollectionUtils;
import com.alibaba.excel.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.gson.Gson;
import com.kuaidi100.sdk.api.QueryTrack;
import com.kuaidi100.sdk.request.QueryTrackParam;
import com.kuaidi100.sdk.request.QueryTrackReq;
import com.kuaidi100.sdk.response.QueryTrackResp;
import com.kuaidi100.sdk.utils.PropertiesReader;
import com.kuaidi100.sdk.utils.SignUtils;
import com.ytjj.qmyx.supplychain.common.api.CommonPage;
import com.ytjj.qmyx.supplychain.common.api.CommonResult;
import com.ytjj.qmyx.supplychain.common.api.ResultCode;
import com.ytjj.qmyx.supplychain.common.constants.BankerConstants;
import com.ytjj.qmyx.supplychain.common.constants.RedisConstants;
import com.ytjj.qmyx.supplychain.common.exception.ApiException;
import com.ytjj.qmyx.supplychain.common.model.BankerImportErrorVO;
import com.ytjj.qmyx.supplychain.common.model.dto.ImportErrorDto;
import com.ytjj.qmyx.supplychain.common.model.request.*;
import com.ytjj.qmyx.supplychain.common.model.response.*;
import com.ytjj.qmyx.supplychain.common.utils.ExpressDicUtil;
import com.ytjj.qmyx.supplychain.common.utils.RedisService;
import com.ytjj.qmyx.supplychain.common.utils.TokenUtil;
import com.ytjj.qmyx.supplychain.mapper.*;
import com.ytjj.qmyx.supplychain.mapper.entity.*;
import com.ytjj.qmyx.supplychain.mapper.model.OrderExceptionNoteReq;
import com.ytjj.qmyx.supplychain.service.*;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;
import org.apache.logging.log4j.util.Strings;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.data.projection.Accessor;
import org.springframework.util.Assert;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.stream.Collectors;

/**
 * 订单管理
 */
@Slf4j
@RestController
@RequestMapping("/order")
@RefreshScope
public class OrderController {
    @Resource
    private OrderService orderService;
    @Autowired
    private OrdersInterceptService ordersInterceptService;
    @Autowired
    private BankerOrderService bankerOrderService;
    @Autowired
    private ExpressDicService expressDicService;
    @Resource
    private ReissueLogisticsMapper reissueLogisticsMapper;
    @Autowired
    private RedisService redisService;
    @Resource
    private ExpressDicMapper expressDicMapper;
    @Resource
    private ReturnGoodsMapper returnGoodsMapper;
    @Resource
    private BankerMapper bankerMapper;
    @Resource
    private BankerImportErrorMapper bankerImportErrorMapper;
    @Resource
    private BankerOrderMapper bankerOrderMapper;
    @Resource
    private ExpressDicMapper yxExpressDicMapper;
    @Autowired
    private OrderExceptionService orderExceptionService;
    @Autowired
    private ShopInfoService shopInfoService;
    @Autowired
    private AbroadService abroadService;
    @Resource
    private OrdersMapper ordersMapper;
    @Resource
    private BankerExportRecordService bankerExportRecordService;
    @Resource
    private ExpressOrderService expressOrderService;

    /**
     * 订单附加信息上传阈值
     */
    @Value("${supplychain.order.upload.threshold:500}")
    private Integer threshold;

    /**
     * 订单上传(谷创/聚卖多)
     * @param requestList
     * @return
     */
    @PostMapping("/upload")
    public CommonResult orderUpload(@RequestBody List<OrderUploadRequest> requestList) {
        return CommonResult.success(orderService.orderUpload(requestList));
    }

    /**
     * 订单上传(团购)
     * @param requestList
     * @return
     */
    @PostMapping("/uploadByGroup")
    public Integer uploadByGroup(@RequestBody List<OrderUploadRequest> requestList) {
        return orderService.uploadByGroup(requestList);
    }

    /**
     * 拦截订单
     * @param intercept
     * @return
     */
    @PostMapping("/intercept")
    public CommonResult orderIntercept(@RequestBody YxOrdersIntercept intercept) {
        return ordersInterceptService.addIntercept(intercept) > 0 ? CommonResult.success() : CommonResult.failed("拦截失败");
    }

    /**
     * 更新订单物流单号
     * @return
     */
    @PostMapping("/updateOrderExpressInfo")
    public CommonResult updateOrderExpressInfo(@Validated @RequestBody OrderExpressModifiedRequest request) {
        bankerOrderService.fillEmptyExpress(request);
        return CommonResult.success(ResultCode.SUCCESS);
    }

    /**
     * 插入快递订单表
     * @return
     */
    @PostMapping("/insertExpressOrder")
    public CommonResult insertExpressOrder(@RequestBody YxExpressOrders request) {
        boolean b = orderService.insertExpressOrder(request);
        return b ? CommonResult.success() :CommonResult.failed();
    }

    /**
     * 补订单记录
     */
    @PostMapping("/insertLogistics")
    public CommonResult insertLogistics(@RequestBody YxReissueLogistics request) {
        request.setStatus(0);
        request.setFinishStatus(0);
//        Example example = new Example(YxReissueLogistics.class);
//        example.createCriteria().andEqualTo("childOrderNo",request.getChildOrderNo());
//        List<YxReissueLogistics> yxReissueLogistics = reissueLogisticsMapper.selectByExample(example);
//        if (yxReissueLogistics.size() > 0){
//            return CommonResult.failed("该订单已经有补单数据");
//        }
        request.setId(null);
        return reissueLogisticsMapper.insert(request) > 0 ? CommonResult.success() : CommonResult.failed("补单失败");
    }

    /**
     * 确认补单
     */
    @PostMapping("/updateLogistics")
    public CommonResult updateLogistics(@RequestBody YxReissueLogistics request) {
        log.info("==========updateLogistics============request:{}",request);
        Example example = new Example(YxReissueLogistics.class);
        example.createCriteria().andEqualTo("childOrderNo",request.getChildOrderNo());
        List<YxReissueLogistics> yxReissueLogistics = reissueLogisticsMapper.selectByExample(example);
        AtomicInteger update = new AtomicInteger();
        yxReissueLogistics.stream().forEach(item ->{
            item.setStatus(request.getStatus());
            item.setOperationTime(new Date());
            update.set(reissueLogisticsMapper.updateByPrimaryKeySelective(item));
        });
        return update.get() > 0 ? CommonResult.success() : CommonResult.failed();
    }

    /**
     * 修改补单数据
     */
    @PostMapping("/updateLogisticsDate")
    public CommonResult updateLogisticsDate(@RequestBody YxReissueLogistics request) {
        log.info("==========updateLogisticsDate============request:{}",request);
        Assert.notNull(request.getShopId(),"shopId不能为空");
        Example example = new Example(YxReissueLogistics.class);
        example.createCriteria().andEqualTo("childOrderNo",request.getChildOrderNo()).andEqualTo("reissueLogisticsId",request.getReissueLogisticsId());
        YxReissueLogistics yxReissueLogistics = new YxReissueLogistics();
        yxReissueLogistics.setRecoveryOrderNo(request.getRecoveryOrderNo());
        yxReissueLogistics.setAcquiringDay(request.getAcquiringDay());
        yxReissueLogistics.setShopId(request.getShopId());
        yxReissueLogistics.setProductSkuSpec(request.getProductSkuSpec());
        yxReissueLogistics.setUserAddress(request.getUserAddress());
        yxReissueLogistics.setUserName(request.getUserName());
        yxReissueLogistics.setUserPhone(request.getUserPhone());
        yxReissueLogistics.setDescr(request.getDescr());
        reissueLogisticsMapper.updateByExampleSelective(yxReissueLogistics,example);
        return CommonResult.success();
    }

    /**
     * 销售端删除补单数据同步到供应链
     */
    @GetMapping("/deleteLogistics")
    public Integer deleteLogistics(@RequestParam(name = "childOrderNo") String childOrderNo,@RequestParam(name = "reissueLogisticsId") String reissueLogisticsId){
        log.info("======销售端删除补单数据同步到供应链==========childOrderNo:{},reissueLogisticsId:{}",childOrderNo,reissueLogisticsId);
        return reissueLogisticsMapper.updateDeleteStatus(Integer.parseInt(reissueLogisticsId),childOrderNo);
    }


    @GetMapping("/finishedReissueLogistics")
    public CommonResult finishedReissueLogistics(@RequestParam(name = "finishStatus") String finishStatus,
                                                 @RequestParam(name = "reissueLogisticsId") String reissueLogisticsId,
                                                 @RequestParam(name = "childOrderNo") String childOrderNo) {
        Example example = new Example(YxReissueLogistics.class);
        example.createCriteria().andEqualTo("reissueLogisticsId",Integer.parseInt(reissueLogisticsId)).andEqualTo("childOrderNo",childOrderNo);
        List<YxReissueLogistics> yxReissueLogistics = reissueLogisticsMapper.selectByExample(example);
        if (!CollectionUtils.isEmpty(yxReissueLogistics)) {
            if (finishStatus.equals(0)) {
                reissueLogisticsMapper.updateReissueLogisticsIsFished(Integer.parseInt(reissueLogisticsId),
                        Integer.parseInt(finishStatus), org.apache.commons.lang3.StringUtils.isNoneBlank(yxReissueLogistics.get(0).getExpressNo()) ? 2: 1 ,null);
            } else {
                reissueLogisticsMapper.updateReissueLogisticsIsFished(Integer.parseInt(reissueLogisticsId),
                        Integer.parseInt(finishStatus),3 ,new Date());
            }
        }
        return CommonResult.success();
    }


    @GetMapping("/updateLogisticsReason")
    public CommonResult updateLogisticsReason(@RequestParam(name = "reissueLogisticsId") String reissueLogisticsId,
                                              @RequestParam(name = "logisticsReason") String logisticsReason,
                                              @RequestParam(name = "childOrderNo") String childOrderNo) {
        log.info("修改补单理由参数:reissueLogisticsId:{},logisticsReason:{},shopId:{}",reissueLogisticsId,logisticsReason,childOrderNo);
        reissueLogisticsMapper.updateLogisticsReason(reissueLogisticsId,logisticsReason,childOrderNo);
        return CommonResult.success();
    }



    /**
     * 查询补单处理结果
     * @param shopId
     * @param orderInfoIds
     * @return
     */
    @GetMapping("/queryLogisticsRecord")
    public CommonResult queryLogisticsRecord(@RequestParam(name = "shopId") String shopId,
                                             @RequestParam(name = "orderInfoIds") String orderInfoIds) {
        List<String> orderInfoIdList = Arrays.asList(orderInfoIds.split(","));
        List<Integer> idsInteger = orderInfoIdList.stream().map(Integer::parseInt).collect(Collectors.toList());
        if (idsInteger.size() > 50) {
            throw new ApiException("参数不符合规范,请检查传入参数[订单详情id超长]");
        }
        Example example = new Example(YxReissueLogistics.class);
        example.createCriteria().andEqualTo("shopId", shopId).andIn("orderInfoId", idsInteger);
        example.selectProperties("status", "expressCompanyNo", "expressNo", "orderInfoId","supplementaryDay","reissueLogisticsId",
                "feedbackUrl","logisticsReceiptTime","expressRecord","expressText","refuseReason","finishStatus","finishTime","statusCode","statusDesc","reissueStatus","refuseTime","checkTime","descr");
        List<YxReissueLogistics> list = reissueLogisticsMapper.selectByExample(example);
        List<ReissueLogisticsResponse> result = new ArrayList<>();
        list.stream().forEach(item -> {
            ReissueLogisticsResponse response = new ReissueLogisticsResponse();
            BeanUtils.copyProperties(item, response);
            result.add(response);
        });
        return CommonResult.success(result);
    }

    /**
     * 修改订单信息 (收货人信息,导出信息)
     * @param request
     * @return
     */
    @PostMapping("/updateOrderInfo")
    public CommonResult updateOrderInfo(@RequestBody UpdateOrderInfoRequest request) {
        orderService.updateOrderInfo(request);
        try {
            abroadService.updateAbroadOrder(request);
        } catch (Exception e) {
            log.error("===修改订单上传abroad异常==={}", e);
        }
        return CommonResult.success();
    }

    /**
     * 修改订单签收状态
     *
     * @param childOrderNo
     * @return
     */
    @GetMapping("/updateOrderReceiveStatus")
    public CommonResult updateOrderReceiveStatus(@RequestParam String childOrderNo) {
        return orderService.updateOrderReceiveStatus(childOrderNo);
    }

    /**
     * 更新供应链订单状态
     * 销售端调用 （当销售端退款后，需要修改订单状态）
     * @param request
     * @return
     */
    @PostMapping("/updateOrderStatus")
    public CommonResult updateOrderStatus(@RequestBody UpdateOrderStatusRequest request) {
        log.info("===更新供应链订单状态==={},{},{}", request.getShopId(), request.getChildOrderNo(), request.getOrderStatus());
        orderService.updateOrderStatusByRpc(request.getShopId(), request.getChildOrderNo(), request.getOrderStatus());
        //已关闭订单传数据到大数据中
//        orderService.packParamToKafkaByCompletedOrder(request.getChildOrderNo(),4,null,new Date());
        return CommonResult.success();
    }

    /**
     * 查询订单信息
     * 主要查询物流信息（物流公司编码、快递单号、发货时间）
     * @param request
     * @return
     */
    @PostMapping("/query")
    public CommonResult querySupplyChainOrderInfo(@RequestBody OrderQueryRequest request) {
        return bankerOrderService.querySupplyChainOrderInfo(request.getChildOrderNo());
    }

    /**
     * 查询供应链订单列表
     * @param request
     * @return
     */
    @PostMapping("/getBankerOrderList")
    public CommonResult getBankerOrderList(@RequestBody SupplyChainOrderListRequest request) {
        return CommonResult.success(orderService.getSupplyChainOrderList(request));
    }

    /**
     * 导出商家订单
     */
    @PostMapping("/exportBankerOrderList")
    public CommonResult exportBankerOrderList(@RequestBody SupplyChainOrderListRequest request) throws Exception {
        String url = orderService.exportBankerOrderList(request);
        return CommonResult.success(url);
    }

    /**
     * 导出商家订单
     */
    @PostMapping("/newExportBankerOrderList")
    public CommonResult newExportBankerOrderList(@RequestBody SupplyChainOrderListRequest request, HttpServletResponse response) throws Exception {
        String url = orderService.newExportBankerOrderList(request,response);
        return CommonResult.success(url);
    }

    /**
     * 导出商家订单V2
     */
    @PostMapping("/exportBankerOrderListV2")
    public CommonResult exportBankerOrderListV2(@RequestBody SupplyChainOrderListRequest request, HttpServletResponse response) throws Exception {
        String url = orderService.exportBankerOrderListV2(request,response);
        return CommonResult.success(url);
    }

    /**
     * 导出子订单
     */
    @PostMapping("/exportOrderInfoList")
    public CommonResult exportOrderInfoList(@RequestBody List<OrdersInfoExportResponse> responses) throws IOException {
//        List<OrdersInfoExportResponse> ordersInfoExportResponses = JSONArray.parseArray(exportData, OrdersInfoExportResponse.class);
        String url = orderService.exportOrderInfoList(responses);
        return CommonResult.success(url);
    }

    /**
     * 查询导出商家订单的导出记录
     * @param queryOrderRecordRequest
     * @return
     */
    @PostMapping("/getBankerExportRecordList")
    public CommonResult getBankerExportRecordList(@RequestBody QueryOrderRecordRequest queryOrderRecordRequest) {
        CommonPage commonPage = bankerExportRecordService.getBankerExportRecordList(queryOrderRecordRequest);
        return CommonResult.success(commonPage);
    }


    /**
     * @Description 供应链订单列表 -> 导入快递信息
     * 
     * 
     * @Version 1.0
     **/
    @PostMapping("/importOrdersExpressInfo")
    public CommonResult updateOrdersExpressInfo(@RequestBody SupplyChainImportOrdersExpressListRequest requestList) {
        // 导入订单
        Sheet sheet = new Sheet(1, 1, OrdersExpressRequest.class);
        try {
            List<SupplyChainImportOrdersExpressRequest> list = requestList.getList();
            log.info("读到记录条数：{}", list.size());
            List<YxBankerImportError> errorList = new ArrayList<>();
            List<String> returnGoodsList = new LinkedList<>();

            ImportErrorDto importErrorDto = new ImportErrorDto();
            list = list.stream().filter(s -> !StringUtils.isEmpty(((SupplyChainImportOrdersExpressRequest)s).getExpressNo())).collect(Collectors.toList());

            String redisExpressCompanyVal = redisService.get(RedisConstants.EXPRESS_COMPANY);
            if (StringUtils.isEmpty(redisExpressCompanyVal)) {
                List<YxExpressDic> yxExpressDicList = expressDicMapper.selectAll();
                Map<String, String> map = yxExpressDicList.stream()
                        .collect(Collectors.toMap(YxExpressDic::getExpressKey, YxExpressDic::getExpressValue));
                ExpressDicUtil.into(map);
                redisService.set(RedisConstants.EXPRESS_COMPANY, JSONObject.toJSONString(yxExpressDicList));
                redisService.expire(RedisConstants.EXPRESS_COMPANY, 60 * 60);
            }else {
                List<YxExpressDic> yxExpressDicList = JSONObject.parseArray(redisExpressCompanyVal, YxExpressDic.class);
                Map<String, String> map = yxExpressDicList.stream()
                        .collect(Collectors.toMap(YxExpressDic::getExpressKey, YxExpressDic::getExpressValue));
                ExpressDicUtil.into(map);
            }

            List<String> allReturnGoodsOrderNoList =  new ArrayList<>();

            List<String> childOrderNos = new ArrayList<>();
            list.stream().forEach(item -> {
                SupplyChainImportOrdersExpressRequest request = (SupplyChainImportOrdersExpressRequest) item;
                childOrderNos.add(request.getChildOrderNo());
            });
            LocalDateTime ldt = LocalDateTime.now(ZoneId.systemDefault());
            ldt = ldt.plusMonths(-2);
            Date orderDate = Date.from(ldt.atZone(ZoneId.systemDefault()).toInstant());

            Example example = new Example(YxReturnGoods.class);
            example.createCriteria().andIn("childOrderNo", childOrderNos)
                    .andNotEqualTo("status", 6)
                    .andGreaterThanOrEqualTo("createTime", orderDate);
            List<YxReturnGoods> returnGoods = returnGoodsMapper.selectByExample(example);

            allReturnGoodsOrderNoList = returnGoods.stream().map(YxReturnGoods::getChildOrderNo).collect(Collectors.toList());

            List<String> finalAllReturnGoodsOrderNoList = allReturnGoodsOrderNoList;
            orderService.updateOrdersExpressInfoBySupplyChain(list.stream()
                    .filter(item -> {
                        SupplyChainImportOrdersExpressRequest request = (SupplyChainImportOrdersExpressRequest) item;
                        boolean paramExceptionFlag = false;
                        boolean isContainExpressCompany = false;
                        boolean zeroExpressNoFlag = false;
                        // 参数非法(快递号）
                        if(Strings.isNotEmpty(request.getExpressNo())) {
                            String expressNo = request.getExpressNo().trim();
                            expressNo = expressNo.replaceAll("\\u00A0+|", "");
                            request.setExpressNo(expressNo);
                            paramExceptionFlag = isSpecialChar(request.getExpressNo());
                        }
                        // 参数为空
                        boolean emptyFlag = StringUtils.isEmpty(request.getExpressNo()) || StringUtils.isEmpty(request.getExpressCode());
                        //
                        // 快递公司是否存在
                        if(Strings.isNotEmpty(request.getExpressCode())) {
                            request.setExpressCode(request.getExpressCode().trim());
                            isContainExpressCompany = ExpressDicUtil.containKey(request.getExpressCode());
                        }
                        //校验订单是否退款
                        if (!CollectionUtils.isEmpty(finalAllReturnGoodsOrderNoList) && finalAllReturnGoodsOrderNoList.contains(request.getChildOrderNo())) {
                            returnGoodsList.add(request.getOrderNo());
                            return false;
                        }

                        YxBankerOrder bankerOrder = bankerOrderService.selectByChildOrderNo(request.getChildOrderNo());
                        YxBanker banker = bankerMapper.selectByPrimaryKey(bankerOrder.getBankerId());
                        YxBankerImportError yxBankerImportError = new YxBankerImportError();
                        yxBankerImportError.setBankerId(bankerOrder.getBankerId());
                        yxBankerImportError.setBankerName(banker.getName());
                        yxBankerImportError.setCreateTime(new Date());
                        yxBankerImportError.setOrderNo(((SupplyChainImportOrdersExpressRequest) item).getChildOrderNo());
                        if (!bankerOrder.getOrderInfoStatus().equals(1) && !bankerOrder.getOrderInfoStatus().equals(2)) {
                            yxBankerImportError.setExceptionDes("订单号为" + request.getChildOrderNo() + "的订单状态异常（正常：待发货、已发货）");
                            errorList.add(yxBankerImportError);
                            return false;
                        }
                        if (emptyFlag || paramExceptionFlag || !isContainExpressCompany) {
                            // 状态设置为显示
                            yxBankerImportError.setStatus((byte) 1);
                            // 已经导入过快递
                            List<YxBankerOrder> bankerOrderList = this.getBankerOrderList(request.getChildOrderNo());
                            if(bankerOrderList.size() > 0) {
                                yxBankerImportError.setExceptionDes("订单号为" + request.getChildOrderNo() + "的订单已导入过快递号，请不要重复导入！");
                                bankerImportErrorMapper.insertSelective(yxBankerImportError);
                                errorList.add(yxBankerImportError);
                                return false;
                            }
                            if(emptyFlag) {
                                yxBankerImportError.setExceptionDes("快递号为空的订单，快递单号或快递公司为空，请检查后重试！");
                                bankerImportErrorMapper.insertSelective(yxBankerImportError);
                                errorList.add(yxBankerImportError);
                                return false;
                            }
                            if(paramExceptionFlag) {
                                yxBankerImportError.setExceptionDes("快递号为" + request.getExpressNo() + "的订单录入的快递号包含特殊字符，请检查后重试！");
                                bankerImportErrorMapper.insertSelective(yxBankerImportError);
                                errorList.add(yxBankerImportError);
                                return false;
                            }
                            if(!isContainExpressCompany) {
                                yxBankerImportError.setExceptionDes("快递号为" + request.getExpressNo() + "的订单录入的快递公司名称不存在，请检查后重试！");
                                bankerImportErrorMapper.insertSelective(yxBankerImportError);
                                errorList.add(yxBankerImportError);
                                return false;
                            }

                        }
                        return true;
                    })
                    .map(item -> {
                        ((SupplyChainImportOrdersExpressRequest) item).getExpressNo().trim();
                        ((SupplyChainImportOrdersExpressRequest) item).getExpressCode().trim();
//                        ((OrdersExpressRequest) item).setBankerId(userInfo.getId());

                        return (SupplyChainImportOrdersExpressRequest) item;
                    })
                    .collect(Collectors.toList()));
            importErrorDto.setErrorCount(errorList.size());
            importErrorDto.setSuccessCount(list.size() - errorList.size() - returnGoodsList.size());
            List<BankerImportErrorVO> importErrorVOList = new ArrayList<>();
            errorList.stream().forEach(item -> {
                BankerImportErrorVO vo = new BankerImportErrorVO();
                BeanUtils.copyProperties(item, vo);
                importErrorVOList.add(vo);
            });
            importErrorDto.setErrorList(importErrorVOList);
            importErrorDto.setReturnGoodsList(returnGoodsList);
            return CommonResult.success(importErrorDto);
        } catch (Exception e) {
            e.printStackTrace();
            log.info("导入发生异常：{}", e.getMessage());
        }
        return CommonResult.failed(ResultCode.FAILED);
    }

    public List<YxBankerOrder> getBankerOrderList(String orderNo) {
        Example example = new Example(YxBankerOrder.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("orderNo", orderNo);
        List<YxBankerOrder> bankerOrderList = bankerOrderMapper.selectByExample(example);
        bankerOrderList  = bankerOrderList.stream()
                .filter(item -> !StringUtils.isEmpty(item.getExpressNo()))
                .collect(Collectors.toList());
        return bankerOrderList;
    }

    /**
     * 判断是否含有特殊字符
     *
     * @param str
     * @return true为包含，false为不包含
     */
    public static boolean isSpecialChar(String str) {
        // String regEx = "[ _`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]|\n|\r|\t";
        String regEx = "[ _.`~!@#$%^&*()+=|{}':;',\\[\\]<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。，、？]|\n|\r|\t";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        // 快递单号长度小于6位为非法
        Boolean zeroExpressNoFlag = str.trim().length() < 6;
        return m.find() || zeroExpressNoFlag;
    }

    /**
     * 供应链订单编辑
     * @param orderExpressModifiedRequest
     * @return
     */
    @PostMapping("/fillEmptyExpress")
    public CommonResult fillEmptyExpress(@RequestBody OrderExpressModifiedRequest orderExpressModifiedRequest) {
        orderExpressModifiedRequest.setEnterType(1);
        bankerOrderService.fillEmptyExpress(orderExpressModifiedRequest);
        return CommonResult.success(ResultCode.SUCCESS);
    }

    /**
     * 查询快递公司
     * @return
     */
    @GetMapping("/getExpressList")
    public CommonResult getExpressList() {
        return CommonResult.success(expressDicService.getExpressList());
    }

    /**
     * 供应链订单详情
     * @param orderNo
     * @return
     */
    @GetMapping("/findBankerOrderInfoByNo")
    public CommonResult findBankerOrderInfoByNo(@RequestParam(value = "childOrderNo", required = false) String childOrderNo,
                                                @RequestParam("orderNo") String orderNo) {
        return CommonResult.success(bankerOrderService.findSupplyOrderInfoById(orderNo));
    }

    @GetMapping("/getTest")
    public void getTest(){
        String resp = "{\n" +
                "    \"com\": \"ems\",\n" +
                "    \"condition\": \"00\",\n" +
                "    \"data\": [\n" +
                "        {\n" +
                "                \"time\": \"2023-02-06 10:31:54\",\n" +
                "                \"context\": \"【深圳市】 【南山科技南】 的石威（135****1234） 正在第3次派件, 请保持电话畅通,并耐心等待（95720为中通快递员外呼专属号码，请放心接听）\",\n" +
                "                \"ftime\": \"2023-02-06 10:31:54\",\n" +
                "                \"areaCode\": \"CN440305000000\",\n" +
                "                \"areaName\": \"广东,深圳市,南山区\",\n" +
                "                \"status\": \"签收\",\n" +
                "                \"location\": \"广东省 深圳市 南山科技南\",\n" +
                "                \"areaCenter\": \"113.923552,22.528499\",\n" +
                "                \"areaPinYin\": \"nan shan qu\",\n" +
                "                \"statusCode\": \"304\"\n" +
                "            }\n" +
                "    ],\n" +
                "    \"ischeck\": \"0\",\n" +
                "    \"message\": \"ok\",\n" +
                "    \"nu\": \"123456\",\n" +
                "    \"result\": false,\n" +
                "    \"routeInfo\": {\n" +
                "        \"cur\": {},\n" +
                "        \"from\": {}\n" +
                "    },\n" +
                "    \"state\": \"202\",\n" +
                "    \"status\": \"200\"\n" +
                "}";
        QueryTrackResp queryTrackResps = JSON.parseObject(resp, QueryTrackResp.class);
//        System.out.println("--");
//        YxBankerOrder yxBankerOrder = new YxBankerOrder();
//        yxBankerOrder.setExpressNo("11");
//        yxBankerOrder.setId(2623797);
//        yxBankerOrder.setExpressCode("youzhengbk");
//        yxBankerOrder.setCreateTime(DateUtil.StrToTime("2023-04-24 18:00:00"));
//        QueryTrackResp resp = new QueryTrackResp();
//        resp.setState("-1");
//        YxBankerOrder yxBankerOrder = bankerOrderMapper.selectByPrimaryKey(2623778);
        YxExpressOrders yxExpressOrders = new YxExpressOrders();
        yxExpressOrders.setCompanyNo("ems");
        yxExpressOrders.setExpressEno("123456");
        expressOrderService.handleExceptionOrder(queryTrackResps,yxExpressOrders);
    }


    /**
     * @Description 客服管理-获取异常订单
     * @Version 1.0
     **/
    @PostMapping("/getExceptionOrders")
    public CommonResult getExceptionOrders(@RequestBody ExceptionOrdersRequest exceptionOrdersRequest) {
        log.info("====getExceptionOrders==={}", exceptionOrdersRequest);
        CommonPage<OrdersExceptionResponse> commonPage = orderExceptionService.getExceptionOrders(exceptionOrdersRequest);
        List<OrdersExceptionResponse> OrdersExceptionResponseList = commonPage.getList();
        Set<Integer> bankerIds = OrdersExceptionResponseList.stream().map(OrdersExceptionResponse::getBankerId).collect(Collectors.toSet());
        if(CollectionUtils.isEmpty(OrdersExceptionResponseList)){
            return CommonResult.success(commonPage);
        }
        List<YxBanker> yxBankers = bankerMapper.selectByIds(new ArrayList<>(bankerIds));
        Map<Integer, List<YxBanker>> bankerMap = yxBankers.stream().collect(Collectors.groupingBy(YxBanker::getId));
        commonPage.setList(OrdersExceptionResponseList.stream().map(item -> {
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            if (null != item.getCreateTime()) {
                item.setCreateTimeText(simpleDateFormat.format(item.getCreateTime()));
            }
            if (null != item.getHandleTime()) {
                item.setHandleTimeText(simpleDateFormat.format(item.getHandleTime()));
            }
            if (null != item.getOrderCreateTime()) {
                item.setOrderCreateTimeText(simpleDateFormat.format(item.getOrderCreateTime()));
            }
            if (null != item.getUpdateTime()) {
                item.setUpdateTimeText(simpleDateFormat.format(item.getUpdateTime()));
            }
            //来源是供应链，则显示供应商名称
            if (exceptionOrdersRequest.getRequestType() != null && exceptionOrdersRequest.getRequestType() == 1) {
                if (!CollectionUtils.isEmpty(bankerMap.get(item.getBankerId()))) {
                    item.setBankerName(bankerMap.get(item.getBankerId()).get(0).getName());
                }
            }else {
                item.setBankerName("");
            }
            return item;
        }).collect(Collectors.toList()));
        return CommonResult.success(commonPage);
    }

    /**
     * 供应商异常订单统计
     */
    @PostMapping("/getExceptionOrdersStatistics")
    public CommonResult<List<ExceptionStatisticsResponse>> getExceptionOrdersStatistics(@RequestBody ExceptionOrdersRequest exceptionOrdersRequest) {
        List<ExceptionStatisticsResponse> exceptionOrdersStatistics = orderExceptionService.getExceptionOrdersStatistics(exceptionOrdersRequest);
        return CommonResult.success(exceptionOrdersStatistics);
    }

    /**
     * 供应商异常订单统计
     */
    @GetMapping("/getAllExpressException")
    public CommonResult<Map<String,String>> getAllExpressException() {
        Map<String, String> allExpressException = orderExceptionService.getAllExpressException();
        return CommonResult.success(allExpressException);
    }

    /**
     * 供应商异常订单跟踪页--获取所有的异常订单
     * @param exceptionOrdersRequest
     * @return
     */
    @PostMapping("/getAllExceptionOrders")
    public CommonResult getAllExceptionOrders(@RequestBody ExceptionOrdersRequest exceptionOrdersRequest){
        return CommonResult.success(orderExceptionService.getAllExceptionOrders(exceptionOrdersRequest));
    }

    /**
     * @Description 更新异常订单处理状态
     * @Version 1.0
     **/
    @PostMapping("/updateExceptionHandleStatus")
    public CommonResult<List<ImportExcelFailResponse>> updateExceptionHandleStatus(@RequestBody List<ExceptionOrdersRequest> exceptionOrdersRequest) {
        List<ImportExcelFailResponse> importExcelFailResponse = orderExceptionService.updateExceptionHandle(exceptionOrdersRequest);
        return CommonResult.success(importExcelFailResponse);
    }
    
    
    /**
     * @Description 批量更新异常订单处理状态
     * @Version 1.0
     **/
//    @PostMapping("/batchUpdateExceptionHandleStatus")
//    public CommonResult batchUpdateExceptionHandleStatus(@RequestBody OrderExceptionNoteReq req) {
//    	int[] ids = req.getIds();
//    	for(int i:ids) {
//    		ExceptionOrdersRequest vo = new ExceptionOrdersRequest();
//    		vo.setId(i);
//    		orderExceptionService.updateExceptionHandleStatus(vo);
//    	}
//        return CommonResult.success(ResultCode.SUCCESS);
//    }

    /**
     * 获取快递公司
     * @return
     */
    @GetMapping("/getExpressDic")
    public List<YxExpressDic> getExpressDic(){
        // 数据库读取配置文件
        List<YxExpressDic> yxExpressDicList = yxExpressDicMapper.selectAll();
        return yxExpressDicList;
    }

    /**
     * 对比传过来的子订单号确认是否存在在供应链
     * @return
     */
    @PostMapping("/selectByChildOrderNo")
    public List<String> selectByChildOrderNo(@RequestBody OrderQueryRequest queryRequest){
        return orderService.selectByChildOrderNo(queryRequest.getChildOrderNo());
    }

    /**
     * 查询快递
     */
    @GetMapping("/checkLogistics")
    public Map<String,String> checkLogistics(@RequestParam String expressCompany,@RequestParam String expressNo){
        return orderService.checkLogistics(expressCompany,expressNo);
    }

    /**
     * 销售端修改收货地址
     */
    @PostMapping("/updateAddress")
    public CommonResult updateAddress(@RequestBody ReceiveAddressRequest request){
        return orderService.updateAddress(request);
    }

    /**
     * 订单报关参数上传
     * @param request
     * @return
     */
    @PostMapping("/upload_attach_info")
    public CommonResult uploadAttachInfo(@RequestBody @Valid OrderUploadAttachInfoRequest request) {
        log.info("===uploadAttachInfo===start");
        if (request.getData().size() > threshold) {
            return CommonResult.failed("参数错误：超过最大订单数！");
        }
        if (request.getData().size() <= 0) {
            return CommonResult.failed("参数错误：数据不能为空！");
        }
        String partentId = TokenUtil.getPartentId();
        if (StringUtils.isEmpty(partentId)) {
            return CommonResult.failed("参数错误：partentId不能为空！");
        }
        YxShopInfo shopInfo = shopInfoService.queryShopInfoByPartnerId(partentId);
        if (null == shopInfo) {
            return CommonResult.failed("身份验证失败！");
        }
        Map<String, Object> stringObjectMap = orderService.uploadAttachInfo(request, shopInfo);
        log.info("===uploadAttachInfo===end");
        return CommonResult.success(stringObjectMap);
    }



    /**
     * 推送订单数据到kafka（测试的接口）
     * @param
     * @return
     */
    @GetMapping("/sendOrderMsgToKafka")
    public CommonResult channelPullData(@RequestParam String childOrderNo) {
        //根据子订单号获取 yx_banker_order yx_orders yx_return_duty 的数据
        orderService.checkOrderToKafkaRecord();
        return CommonResult.success();
    }

    /**
     * 获取前多少天的物流信息，并更新物流状态(手动接口请求调用)
     * @param day n天前
     * @return CommonResult
     */
    @GetMapping("/updateOrdersExpressByDay")
    public CommonResult updateOrdersExpressByDay(Integer day,String type,String phone) {
//        List<YxExpressOrders> expressOrdersList = new ArrayList<>();
//        if(StringUtils.isEmpty(type) ){
//            return CommonResult.failed("type值不能为空！1-查近多少天，2-根据手机号操作");
//        }else if("1".equals(type)){
//            expressOrdersList = expressOrderService.getExpressOrderList(day);
//        }else if("2".equals(type)){
//            if(StringUtils.isEmpty(phone)){
//                return CommonResult.failed("手机号不能为空！");
//            }
//            String[] phones = phone.split(",");
//            expressOrdersList = expressOrderService.getExpressOrderByPhone(Arrays.asList(phones));
//        }
//        expressOrdersList.stream().forEach(item -> {
//            QueryTrack queryTrack = new QueryTrack();
//            QueryTrackReq queryTrackReq = new QueryTrackReq();
//            QueryTrackParam queryTrackParam = new QueryTrackParam();
//            queryTrackParam.setCom(item.getCompanyNo());
//            queryTrackParam.setNum(item.getExpressEno());
//            queryTrackParam.setPhone(item.getPhone());
//            queryTrackReq.setParam(queryTrackParam);
//            queryTrackReq.setCustomer(PropertiesReader.get("customer"));
//            queryTrackReq.setSign(SignUtils.sign(new Gson().toJson(queryTrackParam) + PropertiesReader.get("key") + PropertiesReader.get("customer")));
//            QueryTrackResp resp = queryTrack.queryTrack(queryTrackReq);
//            try {
//                log.info("=====【开始】更新订单物流及完成状态：公司：{}，物流单号：{}",item.getCompanyNo(),item.getExpressEno());
//                expressOrderService.handleExpressQueryResp(resp, item);
//                log.info("=====【结束】更新订单物流及完成状态：公司：{}，物流单号：{}",item.getCompanyNo(),item.getExpressEno());
//            } catch (Exception e) {
//                log.error("===阶段定时刷新快递订单状态异常==={}", e);
//            }
//        });
        return CommonResult.success("测试接口已废除不再用！");
    }

    /**
     * 手动更新订单完成状态(手动接口请求调用)
     * @return CommonResult
     */
    @GetMapping("/updateOrderFinished")
    public CommonResult updateOrderFinished() {
        log.info("====开始处理签收7天的订单====");
        List<YxOrders> yxOrders = ordersMapper.selectUnFinishOrdersBetweenTime(7);
        log.info("====当前需要修改成【已完成】状态的订单有："+yxOrders.size()+"单！====");
        if(org.springframework.util.CollectionUtils.isEmpty(yxOrders)){
            return CommonResult.success();
        }
        for (YxOrders yxOrder : yxOrders) {
            orderService.updateOrderFinished(yxOrder);
        }
        return CommonResult.success();
    }

    /**
     * 批量设置订单为已完结
     * @param childOrderNo
     * @param status 0-取消已完成（还原为已发货状态） 1-设置订单为已完成
     * @return
     */
    @GetMapping("/setOrdersFinished")
    public CommonResult setOrdersFinished(String childOrderNo,Integer status) {
        List<YxOrders> yxOrders = ordersMapper.selectByChildOrderNo(Arrays.asList(childOrderNo));
        for (YxOrders order : yxOrders) {
            //取消已完成状态
            if(status == 0){
                if(order.getOrderStatus() != 3){
                    throw new ApiException("订单不是已完成状态，无法取消完成状态！");
                }
                orderService.updateOrderUnFinished(order);
            }else if(status == 1){//设置已完成状态
                if(order.getOrderStatus() != 2){
                    throw new ApiException("订单当前状态不是已发货，无法设置成订单完成！");
                }
                orderService.updateOrderFinished(order);
            }else {
                throw new ApiException("参数错误！");
            }
        }
        return CommonResult.success();
    }


    /**
     * 根据子订单号查询供应商订单信息
     * @param childOrderNo
     * @return
     */
    @GetMapping("/findBankOrdreByChildOrderNo")
    public String findBankOrdreByChildOrderNo(String childOrderNo){
        YxBankerOrder yxBankerOrder = bankerOrderMapper.findByChildOrderNo(childOrderNo);
        if (yxBankerOrder==null || (yxBankerOrder.getOrderInfoStatus().equals(1) && yxBankerOrder.getIsExport()==(byte)0 )){
            return "1";
        }
        return "0";
    }

    /**
     * 修改订单地址
     * @param childOrderNo
     * @param tel
     * @param address
     * @return
     */
    @GetMapping("/updateBankerOrderAddress")
    public String updateBankerOrderAddress(String childOrderNo, String tel, String address,String newTel,String userName){
        log.info("{},{},{},{},{}",childOrderNo,tel,address,newTel,userName);
        bankerOrderMapper.updateBankerOrderAddress(childOrderNo, tel, address,newTel,userName);
        bankerOrderMapper.updateOrderAddress(childOrderNo, tel, address,newTel,userName);
        return "ok";
    }
}
